package chuangyi.com.org.DOMIHome.Fragments;

import android.app.Fragment;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.Toast;

import com.solidfire.gson.internal.LinkedTreeMap;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import chuangyi.com.org.DOMIHome.BR;
import chuangyi.com.org.DOMIHome.HomeActivity;
import chuangyi.com.org.DOMIHome.OnItemClickListener;
import chuangyi.com.org.DOMIHome.R;
import chuangyi.com.org.DOMIHome.RollPagerView;
import chuangyi.com.org.DOMIHome.Utils.Utils;
import chuangyi.com.org.DOMIHome.Utils.ViewUtil;
import chuangyi.com.org.DOMIHome.Utils.WebApi;
import chuangyi.com.org.DOMIHome.adapter.ImageAdapter;
import chuangyi.com.org.DOMIHome.adapter.LoopPagerAdapter;
import chuangyi.com.org.DOMIHome.adapter.StaticPagerAdapter;
import chuangyi.com.org.DOMIHome.databinding.FComunicationBinding;
import chuangyi.com.org.DOMIHome.databinding.FHomeBinding;
import chuangyi.com.org.DOMIHome.databinding.FMineBinding;
import chuangyi.com.org.DOMIHome.databinding.FStudyBinding;
import chuangyi.com.org.DOMIHome.view.TextHintView;
import chuangyi.com.org.ViewModel.BannerItem;
import chuangyi.com.org.ViewModel.CommunicationModel;
import chuangyi.com.org.ViewModel.HomeModel;
import chuangyi.com.org.ViewModel.Mine_HomeModel;
import chuangyi.com.org.ViewModel.StudyModel;
import chuangyi.com.org.ViewModel.TabItem;
import chuangyi.com.org.ViewModel.VideoDetail;
import chuangyi.com.org.ViewModel.WebViewModel;

/**
 * Created by zxh on 16/11/10.
 */

public class HomeFragment extends CommonFragment implements TabHost.TabContentFactory {
    private TabHost tabHost;
    private List<TabItem> tabItems;
    private RollPagerView viewPager;
    //    private TestLoopAdapter mBannerAdapter;
    private NormalAdapter mBannerAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tabItems = new ArrayList<TabItem>();
        TabItem item = new TabItem("LEARN", R.drawable.learn_tabitem, R.layout.f_study, R.layout.tab_item);
        tabItems.add(item);
        item = new TabItem("COMMUNICATE", R.drawable.communicate_tabitem, R.layout.f_comunication, R.layout.tab_item);
        tabItems.add(item);
        item = new TabItem("MY", R.drawable.my_tabitem, R.layout.f_mine, R.layout.tab_item);
        tabItems.add(item);
//        ArrayAdapter<VideoItem> adapter = new ArrayAdapter<VideoItem>(this, R.layout.i_study);
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final HomeModel homeModel = new HomeModel(this.getActivity(), null, tabItems);
        super.setDataModel(homeModel);
        final FHomeBinding binding = DataBindingUtil.inflate(inflater, R.layout.f_home, container, false);
        binding.setVariable(BR.home, getDataModel());
        View view = binding.getRoot();
        Callback callback = getInitCallback();
        if (callback != null) {
            callback.viewCreated(view);
        }

        tabHost = (TabHost) view.findViewById(R.id.customTabHost);
        homeModel.setTopBarVisible(true);
        homeModel.setTabHost(tabHost);
        tabHost.setup();
//        tabHost.getTabWidget().setDividerDrawable(R.mipmap.footerline);
        for (TabItem item : tabItems) {
            TabHost.TabSpec tabItem = tabHost.newTabSpec(item.getTitle());
            LinearLayout tab = (LinearLayout) inflater.inflate(item.getLayout(), null);
            tab.setBackgroundResource(item.getIcon_resource());
            tabItem.setIndicator(tab);
            tabItem.setContent(this);

            tabHost.addTab(tabItem);
        }
        if (savedInstanceState != null && savedInstanceState.containsKey("currentTab")) {
            int currentTab = savedInstanceState.getInt("currentTab");
            tabHost.setCurrentTab(currentTab);
        }

        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
            @Override
            public void onTabChanged(String s) {
                TabItem item = tabItems.get(tabHost.getCurrentTab());
                switch (tabHost.getCurrentTab()) {
                    case 0:
                        homeModel.setTopBarVisible(true);
                        StudyModel studyModel = item == null ? null : (StudyModel) item.getModel();
                        if (studyModel != null) {
                            studyModel.load();
                        }
                    case 1:
                        homeModel.setTopBarVisible(true);
                        break;
                    case 2:
                        homeModel.setTopBarVisible(false);
                        Mine_HomeModel model = item == null ? null : (Mine_HomeModel) item.getModel();
                        if (model != null) {
                            model.load();
                        }
                        break;
                }
            }
        });
        return view;
    }

    @Override
    public View createTabContent(String s) {
        TabItem item = tabItems.get(tabHost.getCurrentTab());
        LayoutInflater inflater = this.getActivity().getLayoutInflater();
        ViewGroup group = null;
        ViewDataBinding dataBinding = null;
        Object model = item.getModel();
//        group = (ViewGroup)inflater.inflate(item.getContent(), tabHost.getTabContentView(), false);
        switch (tabHost.getCurrentTab()) {
            case 0:
                FStudyBinding binding = DataBindingUtil.inflate(inflater, item.getContent(), tabHost.getTabContentView(), false);
                dataBinding = binding;
                if (model == null) {
                    StudyModel studyModel = new StudyModel(this.getActivity());
                    model = studyModel;
                    item.setModel(model);
                    studyModel.load();
                    viewPager = binding.normalViewPager;
                    viewPager.setAdapter(mBannerAdapter = new NormalAdapter(viewPager));
                    viewPager.setHintView(null);
                    viewPager.setPlayDelay(Integer.MAX_VALUE);
                    loadBanner();
                }
                binding.setStudy((StudyModel) model);
                break;
            case 1:
                FComunicationBinding comunicationBinding = DataBindingUtil.inflate(inflater, item.getContent(), tabHost.getTabContentView(), false);
                dataBinding = comunicationBinding;
                if (model == null) {
                    CommunicationModel communicationModel = new CommunicationModel(this.getActivity());
                    model = communicationModel;
                    item.setModel(model);
                }
                comunicationBinding.setVariable(BR.communication, model);
                break;
            case 2:
                FMineBinding mineBinding = DataBindingUtil.inflate(inflater, item.getContent(), tabHost.getTabContentView(), false);
                dataBinding = mineBinding;
                if (model == null) {
                    Mine_HomeModel homeModel = new Mine_HomeModel(this.getActivity());
                    model = homeModel;
                    item.setModel(model);
                }
                mineBinding.setModel((Mine_HomeModel) model);
                break;
        }
        return dataBinding == null ? group : dataBinding.getRoot();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    /**
     * 加载轮播图
     */
    private void loadBanner() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final ArrayList<BannerItem> bannerList = new ArrayList<BannerItem>();
                ArrayList list = WebApi.getBanner(getActivity());
                try {
                    for (Object item : list) {
                        LinkedTreeMap map = (LinkedTreeMap) item;
                        BannerItem bannerItem = new BannerItem();
                        bannerItem.setImg((String) map.get("img"));
                        bannerItem.setTid(Utils.getIntValue(map.get("tid")));
                        if (bannerItem.getTid() == 32) {
                            bannerItem.setUrl((String) map.get("url"));
                        } else {
                            bannerItem.setVideoId(Utils.getIntValue(map.get("url")));
                        }
                        bannerList.add(bannerItem);
                    }
                } catch (Exception ex) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(), "解析数据时发生错误", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mBannerAdapter.setImgs(bannerList);
                    }
                });
            }
        }).start();
    }

    private class NormalAdapter extends StaticPagerAdapter {

        ArrayList<BannerItem> imgs;

        public NormalAdapter(RollPagerView viewPager) {

        }

        public void setImgs(ArrayList<BannerItem> imgs) {
            this.imgs = imgs;
            notifyDataSetChanged();
        }

        @Override
        public View getView(ViewGroup container, int position) {
            ImageView view = new ImageView(container.getContext());
            final BannerItem item = imgs.get(position);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getTid() == 33) {
                        // 打开视频详情
                        final CommonFragment fragment = HomeActivity.openVideoDetail(getActivity(),
                                item.getVideoId(), null);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    VideoDetail detail = WebApi.getVideoDetail(getActivity(), item.getVideoId());
                                    fragment.setDataModel(detail);
                                } catch (Exception ex) {

                                }
                            }
                        }).start();
                    } else {
                        // 打开网页
                        WebViewModel model = new WebViewModel(getActivity());
                        CommonFragment fragment = new CommonFragment();
                        fragment.setDataModel(model);
                        model.setUrl(item.getUrl());
                        fragment.setVariableId(BR.webModel);
                        fragment.setLayoutId(R.layout.f_webview);
                        HomeActivity.switchFragment(getActivity(), fragment);
                    }
                }
            });
//            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setMaxWidth(viewPager.getWidth());
            view.setMaxHeight(viewPager.getHeight());
            view.setScaleType(ImageView.ScaleType.FIT_XY);
            view.setAdjustViewBounds(true);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            ViewUtil.imageLoader(view, item.getImg());
            return view;
        }

        @Override
        public int getCount() {
            return imgs == null ? 0 : imgs.size();
        }
    }

    private class TestLoopAdapter extends LoopPagerAdapter {
        ArrayList<BannerItem> imgs;

        public void setImgs(ArrayList<BannerItem> imgs) {
            this.imgs = imgs;
            notifyDataSetChanged();
        }


        public TestLoopAdapter(RollPagerView viewPager) {
            super(viewPager);
        }

        @Override
        public View getView(ViewGroup container, int position) {

            ImageView view = new ImageView(container.getContext());
            final BannerItem item = imgs.get(position);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (item.getTid() == 33) {
                        // 打开视频详情
                        final CommonFragment fragment = HomeActivity.openVideoDetail(getActivity(),
                                item.getVideoId(), null);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    VideoDetail detail = WebApi.getVideoDetail(getActivity(), item.getVideoId());
                                    fragment.setDataModel(detail);
                                } catch (Exception ex) {

                                }
                            }
                        }).start();
                    } else {
                        // 打开网页
                        WebViewModel model = new WebViewModel(getActivity());
                        CommonFragment fragment = new CommonFragment();
                        fragment.setDataModel(model);
                        model.setUrl(item.getUrl());
                        fragment.setVariableId(BR.webModel);
                        fragment.setLayoutId(R.layout.f_webview);
                        HomeActivity.switchFragment(getActivity(), fragment);
                    }
                }
            });
//            view.setScaleType(ImageView.ScaleType.CENTER_CROP);
            view.setMaxWidth(viewPager.getWidth());
            view.setMaxHeight(viewPager.getHeight());
            view.setScaleType(ImageView.ScaleType.FIT_XY);
            view.setAdjustViewBounds(true);
            view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            ViewUtil.imageLoader(view, item.getImg());
            return view;
        }

        @Override
        public int getRealCount() {
            return imgs == null ? 0 : imgs.size();
        }

    }
}
